<template>
  <div class="nursing-dashboard">
    <!-- 搜索区域 -->
    <el-form inline :model="searchForm" class="search-bar">
      <el-form-item label="老人姓名">
        <el-input v-model="searchForm.oldName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="护理员姓名">
        <el-select v-model="searchForm.nurseName" placeholder="请选择" clearable>
          <el-option 
            v-for="nurseName in NurseNameList" 
            :key="nurseName.value"  
            :label="nurseName.label" 
            :value="nurseName.value" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="护理项目">
        <el-select v-model="searchForm.item" placeholder="请选择" clearable>
          <el-option 
            v-for="option in itemOptions" 
            :key="option.value"  
            :label="option.label" 
            :value="option.value" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="期望服务时间">
        <el-date-picker
          v-model="searchForm.timeRange"
          type="daterange"
          range-separator=" - "
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          clearable
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="default" @click="handleReset">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 状态标签 -->
    <el-radio-group v-model="activeTab" class="status-tabs">
      <el-radio label="pending" @click="handle">待执行</el-radio>
      <el-radio label="executed" @click="handle">已执行</el-radio>
      <el-radio label="canceled" @click="handle">已取消</el-radio>
    </el-radio-group>

    <!-- 数据表格（动态列） -->
    <el-table :data="tableData" border header-align="center" style="width: 100%">
      <template v-for="(col, idx) in columns" :key="idx">
        <el-table-column
          v-if="!col.slot"
          :label="col.label"
          :prop="col.prop"
          :type="col.type"
          :width="col.width"
          :align="col.align"
        />
        <!-- 操作列插槽 -->
        <el-table-column
          v-else
          :label="col.label"
          :width="col.width"
          :align="col.align"
        >
          <template #default="scope">
            <template v-if="activeTab === 'pending'">
              <span class="operate-btn cancel" @click="handleCancel(scope.row)">取消</span>
              <span class="operate-btn view" @click="handleView(scope.row)">查看</span>
              <span class="operate-btn execute" @click="handleExecute(scope.row)">执行</span>
              <span class="operate-btn reschedule" @click="handleReschedule(scope.row)">改期</span>
            </template>
            <template v-else>
              <span class="operate-btn view" @click="handleView(scope.row)">查看</span>
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <!-- 取消原因弹窗 -->
    <el-dialog 
      title="填写取消原因" 
      v-model="cancelDialogVisible" 
      width="400px"
    >
      <el-form 
        :model="cancelForm" 
        :rules="cancelRules" 
        ref="cancelFormRef" 
        label-width="80px"
      >
        <el-form-item label="取消原因" prop="reason">
          <el-input 
            v-model="cancelForm.reason" 
            type="textarea" 
            maxLength="100" 
            show-word-limit 
            placeholder="请输入取消原因（最多100字，禁止表情）"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCancelConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 执行记录弹窗（修复模板语法错误） -->
    <el-dialog 
      title="新增执行记录" 
      v-model="executeDialogVisible" 
      width="600px"
    >
      <el-form 
        :model="executeForm" 
        :rules="executeRules" 
        ref="executeFormRef" 
        label-width="100px"
      >
        <!-- 执行时间 -->
        <el-form-item label="执行时间" prop="executeTime">
          <el-date-picker
            v-model="executeForm.executeTime"
            type="datetime"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY/MM/DD HH:mm:ss"
            placeholder="选择执行时间"
            clearable
          ></el-date-picker>
        </el-form-item>

        <!-- 执行图片 -->
        <el-form-item label="执行图片" prop="executeImage">
          <el-upload
            v-model:file-list="uploadFileList"
            accept="image/png,image/jpg,image/jpeg"
            :max-size="2 * 1024 * 1024"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :auto-upload="false"
            list-type="picture-card"
            style="width: 100%"
          >
            <el-button type="primary">点击上传图片</el-button>
            <template #tip>
              <div class="el-upload__tip">支持PNG、JPG、JPEG格式，大小不超过2MB</div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 执行记录 -->
        <el-form-item label="执行记录" prop="executeRecord">
          <el-input 
            v-model="executeForm.executeRecord" 
            type="textarea" 
            maxLength="100" 
            show-word-limit 
            placeholder="请输入执行记录（最多100字，禁止表情）"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="executeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleExecuteConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[3,6,9,12]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; text-align: right;"
    ></el-pagination>
      <!-- 改期弹窗（核心新增） -->
    <el-dialog 
      title="修改执行时间" 
      v-model="rescheduleDialogVisible" 
      width="400px"
    >
      <el-form 
        :model="rescheduleForm" 
        :rules="rescheduleRules" 
        ref="rescheduleFormRef" 
        label-width="120px"
      >
        <el-form-item label="期望服务时间" prop="expectTime">
          <el-date-picker
            v-model="rescheduleForm.expectTime"
            type="datetime"                
            format="YYYY/MM/DD HH:mm:ss"   
            value-format="YYYY/MM/DD HH:mm:ss" 
            placeholder="选择新的期望服务时间"
            :disabled-date="disabledPastTime" 
            clearable
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rescheduleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRescheduleConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import request from '@/utils/request'
import { 
  ElMessage, ElDialog, ElForm, ElFormItem, ElInput, 
  ElSelect, ElOption, ElDatePicker, ElTable, ElTableColumn, 
  ElPagination, ElRadioGroup, ElRadio, ElUpload, ElButton 
} from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { pa } from 'element-plus/es/locales.mjs'

defineOptions({ name: 'NursingDashboard' })
const router = useRouter()
const route = useRoute()
const rescheduleDialogVisible = ref(false)
const currentRescheduleRow = ref({})        // 当前点击改期的行数据
const rescheduleFormRef = ref(null)         // 表单引用（用于校验）
const rescheduleForm = ref({
  expectTime: ''
})
const rescheduleRules = ref({
  expectTime: [
    { required: true, message: '请选择期望服务时间', trigger: 'change' }
  ]
})
// 2. 禁用过去时间（超过当前时间的日期置灰不可选）
const disabledPastTime = (time) => {
  const now = new Date()
  // 比较选择的时间与当前时间，过去的时间返回true（禁用）
  return time.getTime() < now.getTime()
}
// 4. 点击【确定】按钮：校验表单+调用接口修改时间
const handleRescheduleConfirm = () => {
  rescheduleFormRef.value.validate(async (valid) => {
    if (valid) { // 表单校验通过
      try {
        // 调用后端改期接口（传递唯一标识+新时间）
        const res = await request({
          url: '/nursing/job1/reschedule',  // 后端改期接口地址（需与后端约定）
          method: 'put',
          params: {
            // 用老人姓名+项目名称作为任务唯一标识（可根据实际主键调整）
            oldName: currentRescheduleRow.value.oldName,
            itemName: currentRescheduleRow.value.itemName,
            expectTime: rescheduleForm.value.expectTime  // 新的期望服务时间
          }
        })

        // 接口调用成功处理
        if (res.code === 200) {
          ElMessage.success('改期成功！')
          rescheduleDialogVisible.value = false  // 关闭弹窗
          fetchData()  // 刷新表格数据，显示修改后的时间
        } else {
          ElMessage.error('改期失败：' + (res.msg || '服务器异常'))
        }
      } catch (error) {
        ElMessage.error('网络异常，改期失败')
      }
    }
  })
}
const handleReschedule = (row) => { 
 currentRescheduleRow.value = row          // 保存当前任务行数据
  rescheduleForm.value.expectTime = row.expectTime  // 回显原有期望服务时间
  rescheduleDialogVisible.value = true      // 打开改期弹窗 
}
// 初始化逻辑
onMounted(() => {
  const tabFromQuery = route.query.activeTab
  if (tabFromQuery && ['pending', 'executed', 'canceled'].includes(tabFromQuery)) {
    activeTab.value = tabFromQuery
  }
  fetchNursingItems()
  fetchNursingNurses()
  fetchData()
})

// 状态切换
const activeTab = ref('pending')
const handle = () => {
  setTimeout(() => {
    router.push({
      path: route.path,
      query: { ...route.query, activeTab: activeTab.value }
    })
    ElMessage.success(`已切换到${activeTab.value}状态`)
    fetchData()
  }, 0)
}

// 下拉数据加载
const NurseNameList = ref([])
const fetchNursingNurses = () => {
  request({
    url: '/nursing/job1/nurses',
    method: 'get',
  }).then(res => {
    if (res.code === 200) {
      NurseNameList.value = res.data.map(itemStr => ({ label: itemStr, value: itemStr }))
    }
  })
}

const itemOptions = ref([])
const fetchNursingItems = () => {
  request({
    url: '/nursing/job1/items',
    method: 'get',
  }).then(res => {
    if (res.code === 200) {
      itemOptions.value = res.data.map(itemStr => ({ label: itemStr, value: itemStr }))
    }
  })
}

// 搜索与重置
const searchForm = ref({
  oldName: '',
  nurseName: null,
  item: null,
  timeRange: []
})
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}
const handleReset = () => {
  searchForm.value = { oldName: '', nurseName: null, item: null, timeRange: [] }
  handleSearch()
}

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(6)
const columns = [
  { label: '序号', type: 'index', width: 60 },
  { label: '老人姓名', prop: 'oldName' },
  { label: '床位号', prop: 'bedNo' },
  { label: '护理项目名称', prop: 'itemName' },
  { label: '项目类型', prop: 'itemType' },
  { label: '护理员姓名', prop: 'nurseName' },
  { label: '期望服务时间', prop: 'expectTime' },
  { label: '创建人', prop: 'creator' },
  { label: '创建时间', prop: 'createTime' },
  { label: '关联单据', prop: 'relatedDoc' },
  { label: '操作', width: 180, align: 'center', slot: 'operate' }
]

// 加载列表数据
const fetchData = () => {
  try {
    request({
      url: '/nursing/job1/list',
      method: 'get',
      params: {  
        pageNum: currentPage.value,  
        pageSize: pageSize.value,    
        oldName: searchForm.value.oldName,
        nurseName: searchForm.value.nurseName,
        item: searchForm.value.item,
        timeRange: searchForm.value.timeRange,
        status: activeTab.value,
      }
    }).then(res => {
      if (res.code === 200) {
        tableData.value = res.data.list
        console.log(tableData.value)
        total.value = res.data.total
      }
       
      
    })
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}

// 分页事件
const handleSizeChange = (val) => { 
  pageSize.value = val 
  currentPage.value = 1 
  fetchData() 
}
const handleCurrentChange = (val) => { 
  currentPage.value = val 
  fetchData() 
}

// 取消功能
const cancelDialogVisible = ref(false)
const currentCancelRow = ref({})
const cancelForm = ref({ reason: '' })
const cancelFormRef = ref(null)
const cancelRules = ref({
  reason: [
    { required: true, message: '请输入取消原因', trigger: 'blur' },
    { max: 100, message: '最多输入100个字符', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        const emojiReg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122|\u2328|\u3030|\u303D|\u2194|\u2195|\u260E|\u2611|\u2614-\u2618|\u2620|\u2622|\u2623|\u2626|\u262A|\u262E|\u262F|\u2638-\u263A|\u2648-\u2653|\u2660|\u2663|\u2665-\u2666|\u2668|\u267B|\u267F|\u2692-\u2697|\u2699|\u269B-\u269C|\u26A0-\u26A1|\u26AA|\u26AB|\u26B0-\u26B1|\u26BD|\u26BE|\u26C4-\u26C5|\u26C8|\u26CE-\u26CF|\u26D1|\u26D3-\u26D4|\u26E9-\u26EA|\u26F0-\u26F5|\u26F7-\u26FA|\u26FD|\u2702|\u2705|\u2708-\u270D|\u270F|\u2712|\u2714|\u2716|\u271D|\u2721|\u2728|\u2733-\u2734|\u2744|\u2747|\u274C|\u274E|\u2753-\u2755|\u2757|\u2763-\u2764|\u2795-\u2797|\u27A1|\u27B0|\u27BF|\u2934-\u2935|\u2B05-\u2B07|\u2B1B-\u2B1C|\u2B50|\u2B55|\u3030|\u303D|\u3297|\u3299]/g;
        if (emojiReg.test(value)) {
          callback(new Error('禁止输入表情'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
})

const handleCancel = (row) => {
  currentCancelRow.value = row
  cancelForm.value.reason = ''
  cancelDialogVisible.value = true
}

const handleCancelConfirm = () => {
  cancelFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await request({
          url: '/nursing/job1/cancel', 
          method: 'put',
          data: {
            oldName: currentCancelRow.value.oldName,
            itemName: currentCancelRow.value.itemName,
            reason: cancelForm.value.reason
          }
        })
        if (res.code === 200) {
          ElMessage.success('取消成功！')
          cancelDialogVisible.value = false
          fetchData()
        } else {
          ElMessage.error('取消失败，请重试')
        }
      } catch (error) {
        ElMessage.error('网络异常，取消失败')
      }
    }
  })
}

// 执行功能
const executeDialogVisible = ref(false)
const executeForm = ref({
  executeTime: '',
  executeRecord: ''
})
const executeFormRef = ref(null)
const uploadFileList = ref([])
const currentExecuteRow = ref({})

const executeRules = ref({
  executeTime: [
    { required: true, message: '请选择执行时间', trigger: 'change' }
  ],
  executeImage: [
    { 
      validator: (rule, value, callback) => {
        if (uploadFileList.value.length === 0) {
          callback(new Error('请上传执行图片'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  executeRecord: [
    { required: true, message: '请输入执行记录', trigger: 'blur' },
    { max: 100, message: '最多输入100个字符', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        const emojiReg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122|\u2328|\u3030|\u303D|\u2194|\u2195|\u260E|\u2611|\u2614-\u2618|\u2620|\u2622|\u2623|\u2626|\u262A|\u262E|\u262F|\u2638-\u263A|\u2648-\u2653|\u2660|\u2663|\u2665-\u2666|\u2668|\u267B|\u267F|\u2692-\u2697|\u2699|\u269B-\u269C|\u26A0-\u26A1|\u26AA|\u26AB|\u26B0-\u26B1|\u26BD|\u26BE|\u26C4-\u26C5|\u26C8|\u26CE-\u26CF|\u26D1|\u26D3-\u26D4|\u26E9-\u26EA|\u26F0-\u26F5|\u26F7-\u26FA|\u26FD|\u2702|\u2705|\u2708-\u270D|\u270F|\u2712|\u2714|\u2716|\u271D|\u2721|\u2728|\u2733-\u2734|\u2744|\u2747|\u274C|\u274E|\u2753-\u2755|\u2757|\u2763-\u2764|\u2795-\u2797|\u27A1|\u27B0|\u27BF|\u2934-\u2935|\u2B05-\u2B07|\u2B1B-\u2B1C|\u2B50|\u2B55|\u3030|\u303D|\u3297|\u3299]/g;
        if (emojiReg.test(value)) {
          callback(new Error('禁止输入表情'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
})

const beforeUpload = (file) => {
  const isImage = ['image/png', 'image/jpg', 'image/jpeg'].includes(file.type)
  const isLt2M = file.size <= 2 * 1024 * 1024
  if (!isImage) ElMessage.error('仅支持PNG、JPG、JPEG格式')
  if (!isLt2M) ElMessage.error('图片大小不能超过2MB')
  return isImage && isLt2M
}

const handlePreview = (file) => {
  if (file.raw) {
    const imgUrl = URL.createObjectURL(file.raw)
    // 可扩展：打开图片预览弹窗
  }
}

const handleRemove = (file, fileList) => {
  uploadFileList.value = fileList
}

const handleExecute = (row) => {
  currentExecuteRow.value = row
  // 设置默认时间为当前时间
  const now = new Date()
  const formatTime = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
  executeForm.value.executeTime = formatTime
  uploadFileList.value = []
  executeForm.value.executeRecord = ''
  executeDialogVisible.value = true // 关键：打开弹窗
}

const handleExecuteConfirm = () => {
  executeFormRef.value.validate(async (valid) => {
    if (valid) {
      const formData = new FormData()
      formData.append('executeTime', executeForm.value.executeTime)
      formData.append('executeRecord', executeForm.value.executeRecord)
      formData.append('oldName', currentExecuteRow.value.oldName)
      formData.append('itemName', currentExecuteRow.value.itemName)
      if (uploadFileList.value.length > 0) {
        formData.append('executeImage', uploadFileList.value[0].raw)
      }

      try {
        const res = await request({
          url: '/nursing/job1/execute',
          method: 'put',
          data: formData,
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.code === 200) {
          ElMessage.success('执行记录提交成功！')
          executeDialogVisible.value = false
          fetchData()
        } else {
          ElMessage.error('提交失败，请重试')
        }
      } catch (error) {
        ElMessage.error('网络异常，提交失败')
      }
    }
  })
}

// 其他操作
const handleView = (row) => {  
  router.push({
    path: '/fuwu/reuwu/jobDetail',
    query: {
      oldName: row.oldName,
      itemName: row.itemName,
      bedNo: row.bedNo,
      expectTime: row.expectTime,
      relatedDoc: row.relatedDoc,
      createTime: row.createTime,
      creator: row.creator,
      activeTab: activeTab.value,
      itemType: row.itemType,
    }
  })
}

</script>

<style scoped>
.operate-btn.reschedule:hover {
  color: #2d8cf0;
  text-decoration: underline;
}
.search-bar {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.status-tabs {
  margin: 0 0 16px 16px;
}
.el-radio {
  margin-right: 20px;
}

.el-table {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.el-table th {
  background: #fafafa !important;
}

.operate-btn {
  margin: 0 5px;
  cursor: pointer;
  display: inline-block; /* 确保按钮可点击区域正常 */
}
.cancel { color: red; }
.view, .execute, .reschedule { color: #409eff; }

.el-pagination {
  padding: 16px;
  background: #fff;
  margin-top: 0 !important;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.dialog-footer {
  text-align: right;
}

:deep(.el-upload) {
  margin-top: 8px;
}
</style>